package com.uwlaser.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.uwlaser.base.PageInfo;
import com.uwlaser.base.QueryHelpMybatisPlus;
import com.uwlaser.base.impl.CommonServiceImpl;
import com.uwlaser.domain.FactoryShiftHistory;
import com.uwlaser.service.FactoryModelService;
import com.uwlaser.service.FactoryShiftHistoryService;
import com.uwlaser.service.dto.FactoryShiftDto;
import com.uwlaser.service.dto.FactoryShiftHistoryDto;
import com.uwlaser.service.dto.FactoryShiftHistoryQueryParam;
import com.uwlaser.service.mapper.FactoryShiftHistoryMapper;
import com.uwlaser.utils.ConvertUtil;
import com.uwlaser.utils.PageUtil;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

// 默认不使用缓存
//import org.springframework.cache.annotation.CacheConfig;
//import org.springframework.cache.annotation.CacheEvict;
//import org.springframework.cache.annotation.Cacheable;

/**
 * @author mx
 * @date 2023-01-04
 */
@Service
@AllArgsConstructor
// @CacheConfig(cacheNames = FactoryShiftHistoryService.CACHE_KEY)
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class FactoryShiftHistoryServiceImpl extends CommonServiceImpl<FactoryShiftHistoryMapper, FactoryShiftHistory> implements FactoryShiftHistoryService {

    // private final RedisUtils redisUtils;
    private final FactoryShiftHistoryMapper factoryShiftHistoryMapper;

    private final FactoryModelService factoryModelService;

    @Override
    public PageInfo<FactoryShiftHistoryDto> queryAll(FactoryShiftHistoryQueryParam query, Pageable pageable) {
        IPage<FactoryShiftHistory> queryPage = PageUtil.toMybatisPage(pageable);
        IPage<FactoryShiftHistory> page = factoryShiftHistoryMapper.selectPage(queryPage, QueryHelpMybatisPlus.getPredicate(query));
        return ConvertUtil.convertPage(page, FactoryShiftHistoryDto.class);
    }

    @Override
    public List<FactoryShiftHistoryDto> queryAll(FactoryShiftHistoryQueryParam query) {
        return ConvertUtil.convertList(factoryShiftHistoryMapper.selectList(QueryHelpMybatisPlus.getPredicate(query)), FactoryShiftHistoryDto.class);
    }

    @Override
    public FactoryShiftHistory getById(Integer id) {
        return factoryShiftHistoryMapper.selectById(id);
    }

    @Override
    // @Cacheable(key = "'id:' + #p0")
    public FactoryShiftHistoryDto findById(Integer id) {
        return ConvertUtil.convert(getById(id), FactoryShiftHistoryDto.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insert(FactoryShiftHistoryDto resources) {
        FactoryShiftHistory entity = ConvertUtil.convert(resources, FactoryShiftHistory.class);
        return factoryShiftHistoryMapper.insert(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateById(FactoryShiftHistoryDto resources) {
        FactoryShiftHistory entity = ConvertUtil.convert(resources, FactoryShiftHistory.class);
        int ret = factoryShiftHistoryMapper.updateById(entity);
        // delCaches(resources.id);
        return ret;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeByIds(Set<Integer> ids) {
        // delCaches(ids);
        return factoryShiftHistoryMapper.deleteBatchIds(ids);
    }

    @Override
    public int add(String templateCode) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        //根据模型获取当前班次
        FactoryShiftDto factoryShiftDto = new FactoryShiftDto();
        factoryShiftDto.setTemplateCode(templateCode);
        ResponseEntity condition = factoryModelService.getCondition(factoryShiftDto);
        Object body = condition.getBody();
        List<FactoryShiftDto> factoryShiftDtos = oobjectToList(body, FactoryShiftDto.class);
        //拼装数据
        FactoryShiftHistory fs = new FactoryShiftHistory();
        fs.setTemplateCode(templateCode);
        fs.setDataJson(JSONObject.toJSONString(factoryShiftDtos));
        fs.setDateTime(format.format(new Date()));
        return factoryShiftHistoryMapper.insert(fs);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeById(Integer id) {
        Set<Integer> set = new HashSet<>(1);
        set.add(id);
        return this.removeByIds(set);
    }

    /*
    private void delCaches(Integer id) {
        redisUtils.delByKey(CACHE_KEY + "::id:", id);
    }

    private void delCaches(Set<Integer> ids) {
        for (Integer id: ids) {
            delCaches(id);
        }
    }*/

    /*
    @Override
    public void download(List<FactoryShiftHistoryDto> all, HttpServletResponse response) throws IOException {
      List<Map<String, Object>> list = new ArrayList<>();
      for (FactoryShiftHistoryDto factoryShiftHistory : all) {
        Map<String,Object> map = new LinkedHashMap<>();
              map.put("所属模型", factoryShiftHistory.getTemplateCode());
              map.put("创建时间", factoryShiftHistory.getCreateTime());
              map.put("日期", factoryShiftHistory.getDateTime());
              map.put("数据json", factoryShiftHistory.getDataJson());
        list.add(map);
      }
      FileUtil.downloadExcel(list, response);
    }*/

    /**
     * object 转 list
     *
     * @param obj   需要转换的List对象
     * @param clazz List中元素的class
     * @param <T>
     * @return
     */
    public static <T> List<T> oobjectToList(Object obj, Class<T> clazz) {
        List<T> result = new ArrayList<T>();
        // 判断 obj 是否包含 List 类型
        if (obj instanceof List<?>) {
            for (Object o : (List<?>) obj) {
                // 使用Class.cast做类型转换
                result.add(clazz.cast(o));
            }
            return result;
        }
        return null;
    }
}
